package com.abu.crms.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.abu.common.Resp;
import com.abu.common.exception.CRException;
import com.abu.crms.mapper.UserMapper;
import com.abu.crms.pojo.User;
import com.abu.crms.service.AuthService;
import com.abu.crms.utils.JwtProperties;
import com.abu.crms.utils.JwtUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.security.PrivateKey;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@Service
@Slf4j
@EnableConfigurationProperties(JwtProperties.class)
public class AuthServiceImpl implements AuthService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JwtProperties jwtProperties;


    /**
     * 第三方授权登录
     *
     * @param data
     * @return
     */
    @Override
    public String toLogin(Object data) {
        JSONObject jsonObjectData = JSONUtil.parseObj(data);
//        解析获取基本信息
//        用户名
        String username = jsonObjectData.getStr("username");
//        头像
        String avatar = jsonObjectData.getStr("avatar");
        String gender = jsonObjectData.getStr("gender");
//        openId
        String openIdStr = jsonObjectData.getJSONObject("token").getStr("openId");
//        根据openId查询用户是否存在
        User user = this.userMapper.selectOne(new QueryWrapper<User>().eq("open_id", openIdStr).select("user_id"));
        Long userId = null;
//        不存在则将用户先保存，获取userId,生成token返回
        if (user == null) {
            user = new User();
            user
                    .setUsername(username)
                    .setOpenId(openIdStr)
                    .setUserSex(StrUtil.equals(gender, "MALE") ? "男" : "女")
                    .setImg(avatar);
//            用户保存
            int count = this.userMapper.insert(user);
            if (count == 1) {
//                获取id
                userId = user.getUserId();
            }
//            生成token并返回
            return this.getToken(userId, username);
        }
        Long fromDbUserId = user.getUserId();
//        用户存在获取userId,生成token返回
        return this.getToken(fromDbUserId, username);
    }

    private String getToken(Long userId, String username) {
        //        生成token
//        1.载荷内容
        Map<String, Object> tokenContent = new HashMap<>(2);
        tokenContent.put("userId", userId);
        tokenContent.put("username", username);
//        2.获取私钥
        PrivateKey privateKey = jwtProperties.getPrivateKey();
        int expireTime = jwtProperties.getExpire();
        String token = null;
        try {
            token = JwtUtils.generateToken(tokenContent, privateKey, expireTime * 16);
        } catch (Exception e) {
            log.error("生成token失败，原因为：{}", e.getMessage());
        }
        return "UserLogin" + token;
    }
}
